package com.rockcent.mall.lib.helper;

import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.FundTransactionFlow;
import com.rockcent.mall.lib.domain.enumclass.MerchantFundFlowTransactionType;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * Created by HK on 16/11/4.
 */
@Component
public class BaseMerchantFundFlowHelper {

    /**
     * 封装商家资金
     *
     * @param merchantFund          商家资金
     * @param merchantOrder         商家叮当
     * @param changeAvailableAmount 需要改变的可以用金额
     * @param changeFrozen          需要改变的冻结金额
     * @param operationAmount       操作金额
     * @param verifyCount           核销数
     * @param transactionFlow       交易方向
     * @param transactionType       交易类型
     * @return
     */
    public MerchantFundFlow create(MerchantFund merchantFund, MerchantOrder merchantOrder, BigDecimal changeAvailableAmount, BigDecimal changeFrozen, BigDecimal operationAmount, Long verifyCount, FundTransactionFlow transactionFlow, MerchantFundFlowTransactionType transactionType) {
        MerchantFundFlow merchantFundFlow = new MerchantFundFlow();

        if (transactionFlow == FundTransactionFlow.INCOME) {
            merchantFundFlow.setAvailableAmount(merchantFund.getAvailableAmount().add(changeAvailableAmount));
            merchantFundFlow.setFrozen(merchantFund.getFrozen().add(changeFrozen));
        }
        if (transactionFlow == FundTransactionFlow.EXPEND) {
            if ( BigDecimal.valueOf(0L).compareTo(changeAvailableAmount) > 0) {
                merchantFundFlow.setAvailableAmount(merchantFund.getAvailableAmount().add(changeAvailableAmount));
            } else {
                merchantFundFlow.setAvailableAmount(merchantFund.getAvailableAmount().subtract(changeAvailableAmount));
            }
            if (BigDecimal.valueOf(0L).compareTo(changeFrozen) > 0) {
                merchantFundFlow.setFrozen(merchantFund.getFrozen().add(changeFrozen));
            } else {
                merchantFundFlow.setFrozen(merchantFund.getFrozen().subtract(changeFrozen));
            }


        }

        // 当这笔资金变动为服务核销时，这个字段不能为空
        if (verifyCount != null) {
            merchantFundFlow.setVerifyCount(verifyCount);
        }

        merchantFundFlow.setTotalAmount(merchantFundFlow.getAvailableAmount().add(merchantFundFlow.getFrozen()));
        merchantFundFlow.setOperationAmount(operationAmount);
        merchantFundFlow.setMallId(merchantOrder.getMallId());
        merchantFundFlow.setMerchantId(merchantOrder.getMerchantId());
        merchantFundFlow.setMerchantOrderNum(merchantOrder.getOrderNum());
        merchantFundFlow.setMerchantFundId(merchantFund.getId());
        merchantFundFlow.setTransactionFlow(transactionFlow);
        merchantFundFlow.setTransactionType(transactionType);
        merchantFundFlow.setRemark(transactionType.getValue());
        return merchantFundFlow;
    }


}
